/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kedacom.demo.jmx.book;


import com.sun.jdmk.comm.HtmlAdaptorServer;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

/**
 *
 * @author Administrator
 */
public class JMXBookAgent {

    private MBeanServer server = null;

    public JMXBookAgent() {

        System.out.println("/n/tCREATE the MBeanServer .");

        server = MBeanServerFactory.createMBeanServer("JMXBookAgent");

        startHTMLAdapter();

        startRMIConnector();

    }

    protected void startHTMLAdapter() {

        HtmlAdaptorServer adapter = new HtmlAdaptorServer();

        ObjectName adapterName = null;



        try {

            adapter.setPort(9082);

            //create the HTML adapter

            adapterName = new ObjectName("JMXBookAgent :name=html,port=9092");

            server.registerMBean(adapter, adapterName);

            adapter.start();

        }
        catch (Exception e) {

            ExceptionUtil.printException(e);

            System.out.println("Error Starting HTML Adapter for Agent");

        }

    }

    protected void startRMIConnector() {

        //RmiConnectorServer connector = new RmiConnectorServer();

       //ObjectName connectorName = null;



        try {
            
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2099/server");
            JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);//根据给出的地址创建一个服务端，但并不马启动服务，得调用START方法来启动它。 
            cs.start();
            /** 这是书本给出的代码，现在已经不支持了 
            connector.setPort(2099);

            connectorName = new ObjectName("JMXBookAgent :name=RMIConnector");

            server.registerMBean(connector, connectorName);

            connector.start();
             */

        }
        catch (Exception e) {

            ExceptionUtil.printException(e);

        }

    }

    public static void main(String[] args) {

        System.out.println("/n~~~~~~~~~~~~~~~~~~~~~~~");

        System.out.println("/n>>> START of JMXBook Agent");

        System.out.println("/n>>> CREATE the agent ...");

        JMXBookAgent agent = new JMXBookAgent();

        System.out.println("/nAgent is Ready for Service.../n");

    }
}
